from aiogram import types
from aiogram_dialog import DialogManager
from fluentogram import TranslatorRunner

from src.core.exceptions.subscription import (
    AddedCalendarsLimitReached,
    CalendarAlreadyAdded,
)
from src.database.services import CalendarService


async def assign_calendar_to_user(
    call: types.CallbackQuery, __, manager: DialogManager
):
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    calendar_service: CalendarService = manager.middleware_data.get("calendar_service")

    calendar_id: int = manager.dialog_data.get("calendar_id")
    try:
        await calendar_service.assign_calendar_to_user(
            calendar_id, manager.event.from_user.id
        )
    except AddedCalendarsLimitReached:
        await call.answer(locale.get("added-calendars-limit-reached"))
        return
    except CalendarAlreadyAdded:
        await call.answer(locale.get("calendar-already-added"))
        return

    await call.answer(locale.get("calendar-added-msg"))

    await manager.done()
